1

谁能解释我,我怎样才能让每个 ImageView 循环。当我单击 BACK 按钮时,我想将状态保存到文件中?

也许其他解决方案?谢谢!

activity_view_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content" >

    <ImageView
            android:id="@+id/icon"
            android:layout_width="48px"
            android:layout_height="48px"
            android:layout_marginLeft="4px"
            android:layout_marginRight="10px"
            android:layout_marginTop="8px"
            android:src="@drawable/ic_launcher" >
    </ImageView>

    <TextView
            android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@+id/label"
            android:textSize="46px" >
    </TextView>

</LinearLayout>

视图列表.java

package com.shvedchenko.skleroshop;

    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Environment;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.Toast;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Scanner;


public class ViewList extends ListActivity {

    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;
    private String emptyList = "The SkleroList is empty";
    private String listName;
    private int ln;
    final String DIR_SD = "SkleroShop";
    private MyArrayAdapter madapter;
    private String fileList[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_view_list);
        lvItem = (ListView)this.findViewById(R.id.listView_items);
        Intent intent = getIntent();
        String list = intent.getStringExtra("main");
        listName = list;
        viewList(list);

    }


    public int count(String filename) throws IOException {

        int lines = 0;
        try {

            BufferedReader reader = new BufferedReader(new FileReader(filename));
            while (reader.readLine() != null) lines++;
            reader.close();

        } catch (IOException ex) {
            Toast.makeText(this,"No File",Toast.LENGTH_SHORT).show();
        }
        return lines;
    }

    private void viewList(String list){

        //String fileName = "data/data/com.shvedchenko.skleroshop/files/"+list;

        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this,"SD-карта не доступна: " + Environment.getExternalStorageState(),Toast.LENGTH_LONG).show();
            return;
        }

        // получаем путь к SD
        File sdPath = Environment.getExternalStorageDirectory();
        // добавляем свой каталог к пути
        sdPath = new File(sdPath.getAbsolutePath() + "/" + DIR_SD);
        File sdFile = new File(sdPath, list);

        try {

            ln = count(sdFile.toString());

        }

        catch (IOException ex) {
            Toast.makeText(this,"No File",Toast.LENGTH_SHORT).show();
        }

        fileList = new String[ln];

        try {

            if (!sdPath.exists()) {
                sdPath.mkdirs();
            } else {

                FileInputStream fis = new FileInputStream(sdFile);
                Scanner scanner = new Scanner(fis);

                int counter = 0;

                while(scanner.hasNextLine()){
                    fileList[counter] = scanner.nextLine();
                    counter++;
                }
            }

            setListAdapter(new MyArrayAdapter(this, fileList));

        }
        catch (java.io.FileNotFoundException e) {
            Toast.makeText(this,"Wrong SkleroShop ListName",Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            //int count = getListAdapter().getCount();

            madapter = new MyArrayAdapter(this,fileList);
            int count = madapter.getCount();
            madapter.getItem(0);

            /*for(int i = 0; i < count; i++) {
                Object v = getListAdapter().getItem(i);
                Toast.makeText(this,v.toString(),Toast.LENGTH_SHORT).show();
            }*/





            /*startActivity(intent);
            ViewList.this.finish();
            return false;*/
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.list, menu);
        return true;
    }

}

MyArrayAdapter.java

    package com.shvedchenko.skleroshop;

    import android.app.Activity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;

public class MyArrayAdapter extends ArrayAdapter<String> {
    private final Activity context;
    private final String[] names;

    public MyArrayAdapter(Activity context, String[] names) {
        super(context, R.layout.activity_view_list, names);
        this.context = context;
        this.names = names;
    }

    // Класс для сохранения во внешний класс и для ограничения доступа
    // из потомков класса
    static class ViewHolder {
        public ImageView imageView;
        public TextView textView;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // ViewHolder буферизирует оценку различных полей шаблона элемента

        ViewHolder holder;
        // Очищает сущетсвующий шаблон, если параметр задан
        // Работает только если базовый шаблон для всех классов один и тот же
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.activity_view_list, null, true);
            holder = new ViewHolder();
            holder.textView = (TextView) rowView.findViewById(R.id.label);
            holder.imageView = (ImageView) rowView.findViewById(R.id.icon);
            rowView.setTag(holder);
        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        final OnClickListener makeListener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                LinearLayout ll = (LinearLayout)v.getParent();
                ImageView iv = (ImageView)ll.getChildAt(0);

                assert(R.id.icon == iv.getId());
                Integer integer = (Integer) iv.getTag();
                integer = integer == null ? 0 : integer;

                switch(integer) {

                    case R.drawable.yes:
                        iv.setImageResource(R.drawable.no);
                        iv.setTag(R.drawable.no);

                        break;

                    case R.drawable.no:

                    default:
                        iv.setImageResource(R.drawable.yes);
                        iv.setTag(R.drawable.yes);
                        break;
                }

            }
        };
        //holder.textView.setOnClickListener(makeListener);
        holder.imageView.setOnClickListener(makeListener);

        holder.textView.setText(names[position]);
        // Изменение иконки для Windows и iPhone
        String s = names[position];
        /*if (s.startsWith("Windows7") || s.startsWith("iPhone")
                || s.startsWith("Solaris")) {

            holder.imageView.setImageResource(R.drawable.no);
        } else {
            holder.imageView.setImageResource(R.drawable.yes);
        }*/

        holder.imageView.setImageResource(R.drawable.no);
        holder.imageView.setTag(names[position]);

        return rowView;
    }
}
4

1 回答 1

0

创建一个 ImageView 数组并在您的数组适配器中iv.setImageResource(R.drawable.yes);执行此操作ivarray[x].setImageResource(R.drawable.yes),并为列表的每一行设置一个递增 x 的计数器。

于 2013-08-13T14:25:00.503 回答