简体   繁体   中英

How to inflate views programmatically in vertical order

I just picked up Android developing. I decided to make a ToDo-list(simple and has a somewhat visual body) but I'm facing problems with inflating Layout in order.

Basically I have an Activity that collects information that is supposed to be shown in Main Activity. I get one of them showing up, but can't figure out how to add more than one of them. They'd be showing up in vertical order as the title says.

Main:

package com.example.victor.todo;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

String NEW_TASK, NEW_TASK_DETAILS;
int pos = 1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if (id == R.id.action_add_task){
        Intent i =  new Intent(this,AddTaskActivity.class);
        startActivityForResult(i, 1);
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == 1){
        if(resultCode == RESULT_OK){
            String task = data.getStringExtra("task");
            String taskDetails = data.getStringExtra("details");

            String taskInfo = data.getStringExtra(AddTaskActivity.EXTRA_NAME);

            Log.i("TAG", "task: " + task);
            Log.i("TAG", "task info: " + taskDetails);

            AddTask(task, taskDetails);

        } else {
            //DO SOMETHING IF NO INFO IS RETURNED
        }
    }
}
public void AddTask(String task, String details){
    TextView tw = (TextView)findViewById(R.id.addMainHint);
    ((ViewManager) tw.getParent()).removeView(tw);

    LinearLayout linearLayoutMain = (LinearLayout) findViewById(R.id.mainLinearLayout);

    View v = getLayoutInflater().inflate(R.layout.task_listing, null);

    linearLayoutMain.addView(v);

    TextView taskName = (TextView) v.findViewById(R.id.single_task_info);
    taskName.setText(task);

    CheckBox taskCheckBox = (CheckBox) v.findViewById(R.id.single_task_checkbox);
    taskCheckBox.setChecked(false);

    /*
    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.single_task_layout);
    relativeLayout.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    */

    /*


    RelativeLayout layout = (RelativeLayout) findViewById(R.id.single_task_layout);

    TextView ll = new TextView();
    */

}

public void TaskClicked(){

}

 }

task_listing.xml(a relative layout that acts as the container of the info):

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="70dp"

    android:id="@+id/single_task_layout"
    >

    <TextView
        android:layout_width="300dp"
        android:layout_height="30dp"
        android:id="@+id/single_task_info"
        android:layout_marginTop="20dp"
        android:textColor="@color/primary_material_dark"
        android:textSize="20sp"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="40dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:clickable="true" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/single_task_checkbox"
        android:layout_gravity="left"
        android:layout_toLeftOf="@id/single_task_info"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:enabled="true"
        android:clickable="true"
        android:onClick="TaskClicked"
        android:visibility="visible" />

</RelativeLayout>

I guess I'm using the wrong tools but I don't even know what to search for! I don't have problems with Java itself but the design is giving me serious headache. I've been trying to figure this out for hours(it's 7.48 in the morning)!

Again, it works if I add just one of the layouts so the other javas and xmls aren't probably that important.

Thanks!

Use a listview is correct. Try doing this (A little bit more elaborate than what you have but worth it.

Create a Task object that implements Pacelable. This object can be sent back in the result of AddTaskActivity

public class Task implements Parcelable {
private String myTask;
private String myDetails;

public static final Parcelable.Creator<Task> CREATOR
        = new Parcelable.Creator<Task>() {
    public Task createFromParcel(Parcel in) {
        return new Task(in);
    }

    public Task[] newArray(int size) {
        return new Task[size];
    }
};

public Task() {}

public Task(Parcel in){
    myTask = in.readString();
    myDetails = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(myTask);
    dest.writeString(myDetails);
}

}

And this is your class slightly modified

public class MainActivity extends ActionBarActivity {
private Adapter myAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myAdapter = new Adapter();
    ListView listView = (ListView)findViewById(android.R.id.list);
    listView.setAdapter(myAdapter);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if (id == R.id.action_add_task){
        Intent i =  new Intent(this,AddTaskActivity.class);
        startActivityForResult(i, 1);
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == 1){
        if(resultCode == RESULT_OK){
            myAdapter.addTask(data.getParcelableExtra(AddTaskActivity.[key constant]));

        } else {
            //DO SOMETHING IF NO INFO IS RETURNED
        }
    }
}

public void TaskClicked(){

}

private class Adapter extends BaseAdapter {

    private List<Task> myTasks;

    public Adapter() {
        myTasks = new ArrayList<Task>();
    }

    public void addTask(Task task) {
        myTasks.add(task);
        notifyDataSetChanged();
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView tw = (TextView)findViewById(R.id.addMainHint);
        ((ViewManager) tw.getParent()).removeView(tw);

        convertView = getViewNotNull(convertView, parent);

        Task task = (Task)getItem(position);

        TextView taskName = (TextView) convertView.findViewById(R.id.single_task_info);
        taskName.setText(task.getTask());
    }

    private View getViewNotNull(View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.task_listing)

            //here you should create a viewholder and set it on the view using setTag()
        }
        return convertView;
    }
}

}

I quickly threw this together so hopefully it has what you need to get started you'll still need to implement the item click listener on the listview as well as the check status for the checkboxes

使用ListView轻松完成它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM