ListViewの要素をタップした際に、ListViewを持つActivityに遷移したい
FirstActivityのListViewをタップすると、また別のListViewを持ったSecondViewに遷移させます。設定画面のように実装したいと考えています。
遷移後のSecondActivityにある次のコードでエラーが出ます:
setContentView(listView2);
エラーメッセージはこちらです:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
activity_first.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.hoge.hogehoge.Activity.FirstActivity">
<ListView
android:id="@+id/list_view1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
FirstActivity.java
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
final ListView listView1 = new ListView(this);
setContentView(listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
adapter.add("A"));
adapter.add("B");
adapter.add("C");
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
break;
}
}
});
}
}
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.hoge.hogehoge.Activity.SecondActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/text"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView2" />
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/button"
android:onClick="onClick"/>
</LinearLayout>
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ListView listView2 = (ListView)findViewById(R.id.list_view2);
setContentView(listView2);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1);
adapter.add("D");
adapter.add("E");
adapter.add("F");
listVIew2.setAdapter(adapter);
}