Android studio关于点击事件后的页面跳转,选择完成后返回(onActivityResult)

我这个人喜欢直接上代码,在代码中说明更方便,更直接。

首先在.xml中设置一个button按钮,和一个EditText框,并分别做好id号。

这里我以籍贯测试对象。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_text1a1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
    <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/City"
android:text="籍贯"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextCity"
/> </LinearLayout> 在.java中,将上面的id进行注册,初始化。
之后设置button的点击事件,intent为跳转方法
public class text1A1 extends AppCompatActivity {
private Button City;
private EditText editTextCity; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text1a1);
init();
City.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(text1A1.this,text1A2.class);
startActivityForResult(intent,0); }
});
} 使用onActivityResult方法,对值的调用并返回,这里我设置“giguan”为值的接口返回
 protected void onActivityResult(int A1,int A2,Intent data){
super.onActivityResult(A1,A2,data);
if (A1 == 0 && A2 ==0);
Bundle extras=data.getExtras();
String giguan =extras.getString("giguan");
editTextCity.setText(giguan); } private void init() {
City=(Button)findViewById(R.id.City);
editTextCity=(EditText)findViewById(R.id.editTextCity);
}
} 新建textA2,在textA2的.xml表中建立ListView控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_text1_a2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"> </ListView> </LinearLayout> 在textA2.java表中,依然注册控件,初始化。对应前面的接口,创建数据
public class text1A2 extends AppCompatActivity {
private ListView listView;
private String[] giguan={"非洲","欧洲","亚洲"}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text1_a2);
init();
ArrayAdapter adapter =new ArrayAdapter(text1A2.this,
android.R.layout.simple_list_item_1,giguan);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent =getIntent();
Bundle bundle =new Bundle();
bundle.putString("giguan",giguan[position]);
intent.putExtras(bundle);
text1A2.this.setResult(0,intent);
text1A2.this.finish(); }
});
} private void init() {
listView=(ListView)findViewById(R.id.listView);
}
}

 
 
 
上一篇:Java反射reflection与注解annotation的应用(自动测试机)


下一篇:javascript常用排序算法实现