java - 将记分板添加到 Android Studio 应用程序

标签 java android

我正在尝试向我的 Android Activity 添加记分板,但我在网上找不到任何有用的东西。我无法使用谷歌排行榜,因为我必须向将下载代码并运行它而不是发布的应用程序的人展示我的应用程序。与我一起开发应用程序的人向我发送了这段代码,但它不起作用。如果有人有关于如何从头开始制作记分板的任何好的链接,或者可以告诉我这段代码有什么问题,我将不胜感激

public class Leaderboard extends AppCompatActivity {
    private ListView UsernameList;
    private ListView ScoreList;

    /** Called when the activity is first created */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayAdapter<String> listAdapter;
        ArrayAdapter<Integer> list2Adapter;

        //Find the ListView resources
        UsernameList = (ListView) findViewById(R.id.UsernameList);
        ScoreList = (ListView) findViewById(R.id.ScoreList);

        //Create and populate the list of usernames.
        //This is where the information from the Database would need to be entered. and the String[] removed
        String[] usernames = new String[]{"Andy", "Marie", "George"};
        ArrayList<String> usernameList = new ArrayList<String>();
        usernameList.addAll(Arrays.asList(usernames));

        //Create and populate the list of scores
        //This is where the information from the Database would need to be entered. and the Integer[] removed
        Integer[] scores = new Integer[]{7, 4, 1};
        ArrayList<Integer> scoreList = new ArrayList<Integer>();
        scoreList.addAll(Arrays.asList(scores));

        //Create Array Adapter using the username list
        listAdapter = new ArrayAdapter<String>(this, R.layout.activity_row, usernameList);
        //Add more users
        listAdapter.add("Michael");
        //Set the Array Adapter as the ListView's adapter
        UsernameList.setAdapter(listAdapter);

        //Create Array Adapter using the username list
        list2Adapter = new ArrayAdapter<Integer>(this, R.layout.activity_row, scoreList);
        //Add more users
        list2Adapter.add(0);
        //Set the Array Adapter as the ListView's adapter
        ScoreList.setAdapter(list2Adapter);

    }
}

(这是发送给我的排行榜的java类)

最佳答案

这是我创建的一个演示,使用 sqllite 数据库读取姓名和分数

我称之为记分板

主要 Activity 代码

package com.scroreboard.live.scoreboard;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.scroreboard.live.scoreboard.adapter.CustomListAdapter;
import com.scroreboard.live.scoreboard.model.Items;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private List<Items> itemsList = new ArrayList<Items>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        SQLiteDatabase myDB = null;

        try {

            //Create a Database if doesnt exist otherwise Open It

            myDB = this.openOrCreateDatabase("leaderboard", MODE_PRIVATE, null);

            //Create table in database if it doesnt exist allready

            myDB.execSQL("CREATE TABLE IF NOT EXISTS scores (name TEXT, score TEXT);");

            //Select all rows from the table

            Cursor cursor = myDB.rawQuery("SELECT * FROM scores", null);

            //If there are no rows (data) then insert some in the table

            if (cursor != null) {
                if (cursor.getCount() == 0) {

                    myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Andy', '7');");
                    myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Marie', '4');");
                    myDB.execSQL("INSERT INTO scores (name, score) VALUES ('George', '1');");

                }

            }


        } catch (Exception e) {

        } finally {

            //Initialize and create a new adapter with layout named list found in activity_main layout

            listView = (ListView) findViewById(R.id.list);
            adapter = new CustomListAdapter(this, itemsList);
            listView.setAdapter(adapter);

            Cursor cursor = myDB.rawQuery("SELECT * FROM scores", null);

                if (cursor.moveToFirst()) {

                    //read all rows from the database and add to the Items array

                    while (!cursor.isAfterLast()) {

                        Items items = new Items();

                        items.setName(cursor.getString(0));
                        items.setScore(cursor.getString(1));

                        itemsList.add(items);
                        cursor.moveToNext();


                    }
                }

            //All done, so notify the adapter to populate the list using the Items Array

            adapter.notifyDataSetChanged();
            }

        }

    }

在您的项目中右键单击(在我的例子中)com.scroreboard.live.scoreboard,然后选择new --> package,如图所示

创建 2 个包,一个名为适配器,另一个名为模型

enter image description here

右键单击适配器并选择新建 --> Java 类

将其命名为CustomListAdapter

右键单击模型并选择新建 --> Java 类

将其命名为项目

CustomListAdapter代码

package com.scroreboard.live.scoreboard.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.scroreboard.live.scoreboard.R;
import com.scroreboard.live.scoreboard.model.Items;
import java.util.List;

public class CustomListAdapter extends BaseAdapter {

    private  Context mContext;
    private LayoutInflater inflater;
    private List<Items> itemsItems;



    public CustomListAdapter(Context context, List<Items> itemsItems) {
        this.mContext = context;
        this.itemsItems = itemsItems;

    }

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

    @Override
    public Object getItem(int location) {
        return itemsItems.get(location);
    }

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

    @Override
    public View getView(int position, View scoreView, ViewGroup parent) {
        ViewHolder holder;
        if (inflater == null) {
            inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        if (scoreView == null) {

            scoreView = inflater.inflate(R.layout.list_row, parent, false);
            holder = new ViewHolder();
            holder.name = (TextView) scoreView.findViewById(R.id.name);
            holder.score = (TextView) scoreView.findViewById(R.id.score);

            scoreView.setTag(holder);

        } else {
            holder = (ViewHolder) scoreView.getTag();
        }

        final Items m = itemsItems.get(position);
        holder.name.setText(m.getName());
        holder.score.setText(m.getScore());

        return scoreView;
    }

    static class ViewHolder {

        TextView name;
        TextView score;

    }

}

商品代码

package com.scroreboard.live.scoreboard.model;

public class Items {

    private String name, score;

    public Items() {
    }

    public Items(String name, String score) {

        this.name = name;
        this.score = score;

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getScore() {
        return score;
    }

    public void setScore(String score) {
        this.score = score;
    }
}

还有更多事情。

main_activity布局文件或任何您想要添加ListView的 Activity 布局中添加以下内容(根据您的意愿设置样式)

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="5dp"
    android:clipToPadding="false"
    android:dividerHeight="1dp"
    android:cacheColorHint="#FFFFFF"
    android:layout_marginTop="56dp"/>

最后创建另一个布局资源并将其命名为list_row

其中包含 XML 代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:paddingTop="12dp"
    android:paddingBottom="12dp"
    android:paddingRight="5dp"
    android:paddingLeft="5dp"
    android:descendantFocusability="blocksDescendants">



    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textSize="16dp"
        android:textColor="#222222"/>

    <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="8dp"
        android:textSize="14dp"
        android:textColor="#222222"/>


</RelativeLayout>

好的,一切都完成了,并且应该是不言自明的

完整的应用程序结构

enter image description here

结果

enter image description here

关于java - 将记分板添加到 Android Studio 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34518421/

相关文章:

Java:如何防止使用条件语句将重复项添加到 ArrayList 中?

Android WebView 处理 onReceivedClientCertRequest

java - Apache POI 生成损坏的 Excel 文件

android - 登录后更新同步帐户

android - 您在开发/测试 Android 时使用哪些开源工具?

android - 为什么 genymotion 运行这么慢?

java - Intellij 空 R 文件

java - Android:上传文件和填写POST正文一起

java - 实现HIkariCP时出现ResultSetImpl错误

java - 切换 Activity Android Studio