Есть два активити. Первое(главное) содержит кнопку и пустой список (вначале он пустой), по нажатию на кнопку открывается второе активити и заполняется список (файловый менеджер). Возле списка есть картинки, галочки и т.д. Внизу списка есть кнопка. При выборе элемента из списка и нажатии на кнопку я хочу снова открыть первое активити и заполнить список выбранными элементами из списка со второго активити. Проблема в том, что я не могу заполнить список первого активити. Я не могу его вывести в в Main lyaout.
Теперь чуть подробней:
Активити 2 содержит такой layout
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:descendantFocusability="blocksDescendants" >
<TextView android:id="@+id/titleManager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:textColor="#B22222"
/>
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
<Button
android:id="@+id/button_OK"
android:text="@string/button_OK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:onClick="AddPathToList">
</Button>
</LinearLayout>
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants">
<CheckBox
android:id="@+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</CheckBox>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/tvDescr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text=""
android:textSize="20sp">
</TextView>
</LinearLayout>
<ImageView
android:id="@+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher">
</ImageView>
</LinearLayout>
Для списка из активити 1 я написал второй адаптер.
Вся соль в том, что список, который я заполняю для активити 1, отображается в активити 2, а потом уже запускается активити 1 и список пропадает. Список в активити 1 имеет айди "android:list", такой же как и список в активити 2. Если я пытаюсь задать айдишник в виде "@+id/MyId" и корректирую соответствующую строку в коде
Код: Выделить всё
ListView lvMain = (ListView) findViewById(R.id.MyId); MainActivity.java (активити 1)
Код: Выделить всё
public class MainActivity extends Activity implements OnClickListener {
File path;
Button btnSelectFolder; //Button Select Folder
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Serach button by ID
btnSelectFolder = (Button) findViewById(R.id.button_select_folder);
//Button click
btnSelectFolder.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_select_folder:
// TODO Auto-generated method stub
//Trying to create new activity: file manager
Intent intent = new Intent(this, FileManager_Activity.class);
startActivity(intent);
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Код: Выделить всё
public class FileManager_Activity extends ListActivity {
//private List<String> directoryEntries = new ArrayList<String>();
public static ArrayList<OptionsList> SelectedMusicDirList = new ArrayList<OptionsList>();
private File currentDirectory = new File("/");
private ArrayList<DirectoryList> directoryEntries = new ArrayList<DirectoryList>();
private BoxAdapter boxAdapter;
private OtherBoxAdapter OptionBoxAdapter;
//when new activity starts it uses some layout
@Override
public void onCreate(Bundle iNew) {
super.onCreate(iNew);
//set main layout
setContentView(R.layout.activity_file_manager);
//browse to root directory
browseTo(new File("/"));
}
//browse to file or directory
private void browseTo(final File aDirectory){
//if we want to browse directory
if (aDirectory.isDirectory()){
//fill list with files from this directory
if (aDirectory.canRead()){
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
//set titleManager text
TextView titleManager = (TextView) findViewById(R.id.titleManager);
titleManager.setText(aDirectory.getAbsolutePath());
boxAdapter = new BoxAdapter(this, directoryEntries);
// настраиваем список
ListView lvMain = (ListView) findViewById(android.R.id.list);
lvMain.setAdapter(boxAdapter);
}
else{
//Folder is system and we do not enter
//....
}
}
else {
//if we want to open file, show this dialog:
//listener when YES button clicked
DialogInterface.OnClickListener okButtonListener = new DialogInterface.OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
//intent to navigate file
Intent OpenFileIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("file://" + aDirectory.getAbsolutePath()));
//start this activity
startActivity(OpenFileIntent);
}
};
//listener when NO button clicked
DialogInterface.OnClickListener cancelButtonListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do nothing
}
};
//create dialog
new AlertDialog.Builder(this)
.setTitle("Please, accept your choice...") //title
.setMessage("Do you want to open file "+ aDirectory.getName() + "?") //message
.setPositiveButton("Yes", okButtonListener) //positive button
.setNegativeButton("No", cancelButtonListener) //negative button
.show(); //show dialog
}
}
//fill list
private void fill(File[] files) {
//clear list
directoryEntries.clear();
if (this.currentDirectory.getParent() != null)
directoryEntries.add(new DirectoryList("..","..", R.drawable.ic_launcher, false));
//add every file into list
for (File file : files) {
if (file.canRead()){
directoryEntries.add(new DirectoryList(file.getName(),file.getAbsolutePath(),R.drawable.ic_launcher, false));
}
}
}
//browse to parent directory
private void upOneLevel(){
if(this.currentDirectory.getParent() != null) {
browseTo(currentDirectory.getParentFile());
}
}
//When you click OK Button
public void AddPathToList(View v){
int OptionsSize;
ArrayList<String> FoldersList = new ArrayList<String>();
for(DirectoryList dl : boxAdapter.getBox()){
//If item is checked then boolean box = true
if(dl.box){
FoldersList.add(dl.getPath());
}
}
if (FoldersList.size()!=0){
OptionsSize = SelectedMusicDirList.size();
SelectedMusicDirList.add(new OptionsList("Option " + (OptionsSize + 1) + ".",FoldersList,R.drawable.ic_launcher));
OptionBoxAdapter = new OtherBoxAdapter(this, SelectedMusicDirList);
Intent MainIntent = new Intent(this, MainActivity.class);
startActivity(MainIntent);
// настраиваем список
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setAdapter(OptionBoxAdapter);
}
else{
/*
create dialog when no one where cheked, but button OK was pressed
It means to take current folder
listener when OK button clicked
*/
DialogInterface.OnClickListener OkMusicButtonListener = new DialogInterface.OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
int OptionsSize;
ArrayList<String> NewFoldersList = new ArrayList<String>();
Intent MainIntent;
TextView titleManager;
String FolderPath;
titleManager = (TextView) findViewById(R.id.titleManager);
FolderPath = titleManager.getText().toString();
NewFoldersList.add(FolderPath);
OptionsSize = SelectedMusicDirList.size();
SelectedMusicDirList.add(new OptionsList("Option " + (OptionsSize + 1) + ".",NewFoldersList,R.drawable.ic_launcher));
OptionBoxAdapter = new OtherBoxAdapter(getBaseContext(), SelectedMusicDirList);
// настраиваем список
ListView lvMain = (ListView) findViewById(android.R.id.list);
lvMain.setAdapter(OptionBoxAdapter);
MainIntent = new Intent(getBaseContext(), MainActivity.class);
startActivity(MainIntent);
}
};
//listener when NO button clicked
DialogInterface.OnClickListener CancelMusicButtonListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do nothing
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please, choose folder..."); //title
builder.setMessage("Do you want to add to a list current folder?"); //message
builder.setPositiveButton("Yes", OkMusicButtonListener); //positive button
builder.setNegativeButton("No", CancelMusicButtonListener); //negative button
builder.show(); //show dialog
}
}
//when you clicked onto item
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected file name
DirectoryList selectedFileString= directoryEntries.get(position);
//if we select ".." then go upper
if(selectedFileString.getPath().equals("..")){
upOneLevel();
} else {
//browse to clicked file or directory using browseTo()
File clickedFile = null;
clickedFile = new File(selectedFileString.getPath());
if (clickedFile != null)
browseTo(clickedFile);
}
}
}
Вот как вызываю 1 активити из второго активити:
Код: Выделить всё
OptionsSize = SelectedMusicDirList.size();
SelectedMusicDirList.add(new OptionsList("Option " + (OptionsSize + 1) + ".",FoldersList,R.drawable.ic_launcher));
OptionBoxAdapter = new OtherBoxAdapter(this, SelectedMusicDirList);
Intent MainIntent = new Intent(this, MainActivity.class);
startActivity(MainIntent);
// настраиваем список
ListView lvMain = (ListView) findViewById(android.R.id.list);
lvMain.setAdapter(OptionBoxAdapter);Вот код второго адаптера
Код: Выделить всё
public class OtherBoxAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
ArrayList<OptionsList> objects;
OtherBoxAdapter(Context context, ArrayList<OptionsList> items) {
ctx = context;
objects = items;
//lInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
@Override
public int getCount() {
return objects.size();
}
// элемент по позиции
@Override
public OptionsList getItem(int position) {
return objects.get(position);
}
// id по позиции
@Override
public long getItemId(int position) {
return position;
}
// пункт списка
@Override
public View getView(int position, View convertView, ViewGroup parent) {
lInflater = LayoutInflater.from(ctx);
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.selected_item, parent, false);
}
OptionsList p = getListPosition(position);
//описание и картинка
((TextView) view.findViewById(R.id.OptionDesc)).setText(p.OptionDesc);
((ImageView) view.findViewById(R.id.OptionImage)).setImageResource(p.image);
return view;
}
// позиция
OptionsList getListPosition(int position) {
return ((OptionsList) getItem(position));
}
}