繁体   English   中英

在relativeLayout下动态添加TextView

[英]Adding TextView dynamically under the relativeLayout

在这里输入图像描述,如何动态添加多个已经创建的TextView及其内部相对布局? 我还必须从数据库sqlite调用这些文本框的值。

公共类DownloadPackagesActivity扩展Activity实现AdapterView.OnItemSelectedListener {

private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";

DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download_packages);
    // Get DownloadManager instance
    dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
    subjects = (TextView)findViewById(R.id.subjects);
    // Spinner element
    Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
    // Spinner click listener
    spinner.setOnItemSelectedListener(this);
    // Add textview
    dbHelper = new DBHelper(this);
    try{
        dbHelper.createDataBase();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
    db = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);
    Cursor c = db.rawQuery("select * from DownloadSubject", null);
    while (c.moveToNext()) {
        categories.add(c.getString(1));
    }
    ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
    dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
    spinner.setAdapter(dataAdapter1);
    showPart();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
    SId = position + 1;
    showPart();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
public void showPart()
{
    int j=1;
    int ii=0;
    dbHelper = new DBHelper(this);
    try{
        dbHelper.createDataBase();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    TableLayout stk = (TableLayout) findViewById(R.id.tbl);
    stk.removeAllViews();
    String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
    db = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);
    Cursor c;
    if (SId==8 || SId==9)
    {
        c = db.rawQuery("select * from DownloadSubject", null);
    }
    else
    {
        c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
    }
    while (c.moveToNext())
    {
        subjects.clearComposingText();


        String[] part = c.getString(2).split(",");
        for(int i = 0;i<part.length;i++)
        {

            TableRow tr1 = new TableRow(this);
            Button button = new Button(this);
            button.setBackgroundColor(Color.TRANSPARENT);
            button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
            button.setTextColor(Color.BLUE);
            button.setPadding(20, 0, 0, 0);
            button.setOnClickListener(downloads());
            button.setId(i);
            // button.setHint(part[i]);
            tr1.addView(button);
            stk.addView(tr1);
        }
        stk = (TableLayout) findViewById(R.id.tbl);
        int N = 1;
        TextView[] TextViews = new TextView[N]; // create an empty array;
        // for (int i = 0; i < N; i++) {
        //if(ii!=0) {
        // subjects.setText(c.getString(j));
        // Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();



        // save a reference to the textview for later
        // TextViews[j] = TextView;
        //}
        if(ii==0)
        {
            subjects.setText(c.getString(j));
            ii=ii+1;
        }
        else
        {
            final TextView TextView = new TextView(this);
            TextView.setText(c.getString(j));
            TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
                    TableLayout.LayoutParams.WRAP_CONTENT));
            TextView.setPadding(0, 20, 0, 20);
            TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
            TextView.setTextColor(Color.parseColor("#800080"));
            // add the textview to the layout
            stk.addView(TextView);
        }

    }
}
public String part;
View.OnClickListener downloads()
{
    return new View.OnClickListener()
    {
        public void onClick(View v) {
            //Button b1 = (Button)v;
            //int i  = b1.getId();
            // Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
            part ="";
            TextView subjects = (TextView)findViewById(R.id.subjects);
            if(subjects.getText().toString().equals("Modern History (500 MB)"))
            {
                part = "modern_history";
            }
            else if(subjects.getText().toString().equals("Polity (250 MB)"))
            {
                part = "polity";
            }
            else if(subjects.getText().toString().equals("Economy (100 MB)"))
            {
                part = "economy";
            }
            else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
            {
                part = "ancient_history";
            }
            else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
            {
                part = "english_grammar";
            }
            else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
            {
                part = "vocabulary";
            }
            else if(subjects.getText().toString().equals("Maths (100 MB)"))
            {
                part = "maths";
            }
            else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
            {
                part = "oneday_complete";
            }
            else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
            {
                part = "civil_complete" ;
            }

            newFolder = "/voice";
            subjects = (TextView)findViewById(R.id.subjects);
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File myNewFolder = new File(extStorageDirectory + newFolder);
            //File f = new File(myNewFolder);
            myNewFolder.mkdir();

            Button b = (Button)v;
            FilePart  = b.getText().toString();
            String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
            try {
                urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
                downloadFile();
                Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
            }
            catch(Exception e)
            {
                Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
            }
        }
    };
}
public void downloadFile() {
    // String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
    if (!urlString.equals("")) {
        try {
            // Get file name from the url
            String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
            // Create Download Request object
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
            // Display download progress and status message in notification bar
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            // Set description to display in notification
            // request.setDescription("Download " + fileName + " from " + urlString);
            request.setDescription("Download " + fileName + " from mobileteacher.in");
            // Set title
            request.setTitle("Mobile Teacher");
            // Set destination location for the downloaded file
            request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
            // Download the file if the Download manager is ready
            did = dManager.enqueue(request);
        } catch (Exception e) {
        }
    }
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        DownloadManager.Query q = new DownloadManager.Query();
        q.setFilterById(did);
        Cursor cursor = dManager.query(q);
        if (cursor.moveToFirst()) {
            String message = "";
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            if (status == DownloadManager.STATUS_SUCCESSFUL) {
                message = "Download successful";
            } else if (status == DownloadManager.STATUS_FAILED) {
                message = "Download failed";
            }
            //query.setText(message);
        }
    }
};

protected void onResume() {
    super.onResume();
    // Register the receiver to receive an intent when download complete
    IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    registerReceiver(downloadReceiver, intentFilter);
}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    // Unregister the receiver
    unregisterReceiver(downloadReceiver);
}
@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_download_packages, 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;
    }
    return super.onOptionsItemSelected(item);
}
public void back(View view)
{
    finish();
}
public void Create(View view)
{
    String newFolder = "/voice";
    String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
    myNewFolder.mkdir();
}

}

这是图像

将textview附加到relativelayout非常简单。 只是使用

TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);

设置位置使用textview.setLayoutParams(thelayoutparams)

但是,如果您使用大型数据库,由于性能原因,请使用“ TableLayout”而不是您的方法。

Listview或recyclerview是最佳实践,但由于要使用textview,可以在代码中使用以下代码:

RelativeLayout relativeLayout =
        (RelativeLayout) findViewById(R.id.rootlayout);

    TextView textView = new TextView(this);
    textView.setText("Hey, I am TextView");

    relativeLayout.addView(textView);

根据其布局ID创建相对布局对象,然后可以如下添加它

relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);

在xml布局中定义相对布局。 像这样添加多个textview编程联盟-

  RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        //use a for loop to define multiple textView in RelativeLayout
        //length is no. of textView you required
        for (int i = 0; i < length; i++) {
            TextView tv = new TextView(relativeLayout.getContext());
            tv.setText("Text from sqlite database");
            tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            relativeLayout.addView(tv);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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