android自定义Listview实现

时间:2015-01-04 08:31:48

标签: android listview android-listview

基本上Android列表视图活动是透明的,我已经设法使用自定义布局使其为纯黑色,但我如何使其像角落颜色随机的第三个图像。

提前致谢

MainActivity.java

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ArrayAdapter;

public class MainActivity extends Activity {

// Declare
private LinearLayout slidingPanel;
private boolean isExpanded;
private DisplayMetrics metrics;
private RelativeLayout headerPanel;
private int panelWidth;
private int panelWidth1;


private ImageView menuViewButton,menuRightButton;

FrameLayout.LayoutParams menuPanelParameters;
FrameLayout.LayoutParams slidingPanelParameters;
LinearLayout.LayoutParams headerPanelParameters;
LinearLayout.LayoutParams listViewParameters;

//Example
////////
String[] Example = new String[]
        { "Android Introduction","Android Setup/Installation","Android Hello World",
                "Android Layouts/Viewgroups","Android Activity & Lifecycle","Intents in Android"};


////////
//Example
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layer_stack);

    // Initialize
    metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    panelWidth = (int) ((metrics.widthPixels) * -0.65);//Right panel width
    panelWidth1 = (int) ((metrics.widthPixels) * 0.65);//left panel width

    headerPanel = (RelativeLayout) findViewById(R.id.header);
    headerPanelParameters = (LinearLayout.LayoutParams) headerPanel
            .getLayoutParams();
    headerPanelParameters.width = metrics.widthPixels;
    headerPanel.setLayoutParams(headerPanelParameters);

    slidingPanel = (LinearLayout) findViewById(R.id.slidingPanel);
    slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel
            .getLayoutParams();
    slidingPanelParameters.width = metrics.widthPixels;
    slidingPanel.setLayoutParams(slidingPanelParameters);
    ///////

    ArrayAdapter<String> ExampleArrayAdapter = new CustomAdapter(this, Example);
    //changing code//practice
    /*new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            Example);*/
    ListView ExampleListView = (ListView)findViewById(R.id.listView);
    ExampleListView.setAdapter(ExampleArrayAdapter);
    ///////

    // Slide the Panel
    menuRightButton = (ImageView) findViewById(R.id.menuViewButton);
    menuRightButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!isExpanded) {
                isExpanded = true;
                // Expand

                FragmentManager fragmentManager = getFragmentManager();

                FragmentTransaction fragmentTransaction = fragmentManager
                        .beginTransaction();
                fragmentTransaction.replace(R.id.menuPanel,
                        new LeftMenuFragment());
                fragmentTransaction.commit();
                new ExpandAnimation(slidingPanel, panelWidth1,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.65f, 0, 0.0f, 0, 0.0f);

            } else {
                isExpanded = false;
                // Collapse

                new CollapseAnimation(slidingPanel, panelWidth1,
                        TranslateAnimation.RELATIVE_TO_SELF, 0.65f,
                        TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
                        0, 0.0f);

            }
        }
    });


}
}

custom_layout.xml

<?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="70dp"
android:orientation="horizontal"
android:layout_marginTop="60dp"
android:background="@drawable/blue_bg">

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="70dp"
    android:layout_height="60dp"
    android:src="@drawable/ic_launcher"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp" />


<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginLeft="10dp"
    android:gravity="left" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="19sp"
    android:textColor="#ffffff"
    android:textStyle="bold" />


    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:text="Tweet body text here"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_marginTop="5dp"
    android:ellipsize="end"
    android:lines="3"
    android:textColor="#ffffff"
    android:textSize="14sp" />


    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Small Text"
    android:layout_marginTop="5dp"
    android:textColor="#ffffff"
    android:textSize="12sp" />


</LinearLayout>


</LinearLayout>

CustomAdapter.java

public class CustomAdapter extends ArrayAdapter {
private LayoutInflater inflater;
public CustomAdapter (Activity activity, String[] items){
    super(activity, R.layout.custom_layout, items);
    inflater = activity.getWindow().getLayoutInflater();
}

@Override
public View getView(int position, View convertView, ViewGroup parent){
    return inflater.inflate(R.layout.custom_layout, parent, false);
}
}

我设法让它显示随机颜色,并使用以下代码更新获取视图功能,但每次我滚动颜色更改时,如何使其稳定,以便一旦分配颜色就赢得了#39 ;改变?

 Random rnd = new Random();
    int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));

  View rowView = inflater.inflate(R.layout.custom_layout, parent, false);
    rowView.setBackgroundColor(color);

4 个答案:

答案 0 :(得分:1)

您必须使用具有两个视图的自定义适配器。您可以在适配器的getView方法中更改左视图的颜色。

答案 1 :(得分:1)

最后,我已经对我的问题得到了以下答案但是我仍然面临着问题,每个卷轴上的颜色都在变化,我希望它们在分配后保持不变,如果有人可以帮助它将是大。谢谢你们。通过修改xml和自定义适配器代码,我已将其作为我的xml代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_marginTop="70dp"
android:layout_height="70dp"
android:background="@drawable/blue_bg">

<LinearLayout
    android:layout_marginLeft="20dp"
    android:layout_width="345dp"
    android:layout_height="70dp"
    android:background="@drawable/white_bg">
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="70dp"
        android:layout_height="60dp"
        android:src="@drawable/ic_launcher"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp" />


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="10dp"
        android:gravity="left" >


        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Large Text"
            android:layout_marginTop="10dp"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="19sp"
            android:textColor="#000000"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="15dp"
            android:text="Tweet body text here"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginTop="5dp"
            android:ellipsize="end"
            android:lines="3"
            android:textColor="#000000"
            android:textSize="14sp" />


    </LinearLayout>

</LinearLayout>

</LinearLayout>

使用以下代码修改java代码

 Random rnd = new Random();

   int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258));

  View rowView = inflater.inflate(R.layout.custom_layout, parent, false);
    rowView.setBackgroundColor(color);

答案 2 :(得分:0)

按如下方式创建布局文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" 
    android:weightSum="1">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_weight="0.3" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_weight="0.7" />

</LinearLayout>

你的活动类onCreate()方法看起来应该是这样的。

ListView listView = (ListView) findViewById(R.id.listView1);
String[] Example = new String[] { "Android Introduction",
"Android Setup/Installation", "Android Hello World",
"Android Layouts/Viewgroups", "Android Activity & Lifecycle",
"Intents in Android" };

ArrayList<String> list = (ArrayList<String>) Arrays.asList(Example);
CustomAdapter adapter = new CustomAdapter(this, list);
listView.setAdapter(adapter);

按如下方式创建自定义适配器类。

public class CustomAdapter extends BaseAdapter {
    Context context;
    ArrayList<String> listOfContents;
    LayoutInflater inflater;

    public CustomAdapter(Context context, ArrayList<String> list) {
        this.context = context;
        listOfContents = list;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return listOfContents.size();
    }

    @Override
    public Object getItem(int position) {
        return listOfContents.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = inflater.inflate(R.layout.list_row, null);

        Random rnd = new Random();
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
                rnd.nextInt(256));

        TextView clorText = (TextView) convertView.findViewById(R.id.textView1);
        TextView clorText2 = (TextView) convertView
                .findViewById(R.id.textView2);

        clorText.setBackgroundColor(color);
        clorText2.setBackgroundColor(Color.BLACK);

        return convertView;
    }
}

此代码完全未经测试。您应该大致了解如何使用Listview和Custom适配器并生成随机颜色。

答案 3 :(得分:0)

颜色不断变化,因为列表项被回收,现在当android在滚动时第二次为特定列表项调用getView()方法时,你重新生成颜色值并且它会改变。

因为您可以生成随机颜色,所以您需要做的就是在生成项目后存储颜色,然后重复使用该颜色。

你可以做的是创建一个存储颜色值的数组列表,然后在getView()方法中检查arraylist中是否存在特定位置的颜色。如果是,则使用该颜色生成随机颜色,并将其添加到颜色的arraylist。

E.g。 (未经测试的代码,但方法应该类似)

getView()内部:

int color = 0;
if(colorsList.size > position) {
    //This means that the color has already been generated for this position
    color = colorsList.get(position);
} else {
    //Color hasnt been generated for this position.
    color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
            rnd.nextInt(256));
    colorsList.add(color);
}
clorText.setBackgroundColor(color);