如何从Activity(gridView中的选定项)发送文本到片段并将文本发送到按钮

android gridview adapter

95 观看

1回复

378 作者的声誉

图片

你好guyd。正如你所见,我有活动,游戏片段,适配器

我的活动是gidView,对于这个gridview,我创建了8个项目的ButtonAdapter(按钮)

我想将buttonsNamePostion给gameFragment。

在ButtonAdapter中我得到了Buttons的名字。因此,当我在Activity中我有GridView与Adapter的按钮。我在活动中尝试做类似的事情:

public String setText(){
return gridViewCurrency.getSelectedItemId().toString();
}

然后在GameFragmet中

private void setButtonCurrencyText(){
buttonCurrency.setText(((ActivityCurrency).getContext).setText());
}

但这没有用。

我花了很多时间,我的大脑会爆炸。我怎么能这样做?

问题是。我想从GridView获取ItemName,当我点击item时,我的片段是打开的,而我的buttonCurrency是来自项目点击的文本。帮帮我吧

我不知道该怎么做。

这是活动

公共类CurrencySelectActivity扩展AppCompatActivity {

private final String TAG = this.getClass().getSimpleName();
private GridView gridViewCurrency;
private MainGameFragment mainGameFragment;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_currency_select);
    ButterKnife.bind(this);

    gridViewCurrency = (GridView) findViewById(R.id.gridview);

    configureGridViewCurrencySelect();
}

public void openGameFragment() {
    mainGameFragment = new MainGameFragment();
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.activity_currency_select, mainGameFragment, "fragment")
            .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .commit();
}

public void closerGameFragment() {
    getSupportFragmentManager()
            .beginTransaction()
            .hide(mainGameFragment)
            .commit();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}
private void configureGridViewCurrencySelect() {
    gridViewCurrency.setAdapter(new ButtonAdapter(this));
    gridViewCurrency.setNumColumns(4);

    gridViewCurrency.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(getApplicationContext(), position, Toast.LENGTH_SHORT).show();
        }
    });
}

}

这是ButtonAdapter

public class ButtonAdapter extends BaseAdapter {
private Context mContext;

public ButtonAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return buttonsName.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    Holder holder;
    if (convertView == null) {
        holder = new Holder();
        convertView = LayoutInflater.from(mContext).inflate(R.layout.row_button, null);
        holder.button = (Button) convertView.findViewById(R.id.button);
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((CurrencySelectActivity)mContext).openGameFragment();
            }
        });

        convertView.setTag(holder);

    } else {
        holder = (Holder) convertView.getTag();
    }

    holder.button.setText(buttonsName[position]);
    return convertView;
}

private class Holder {
    private Button button;

}

private String[] buttonsName = {"EUR/USD", "GBP/USD", "USD/CHF", "USD/JPY",
        "EUR/GBP", "EUR/JPN", "EUR/CHF", "USD/NOK",};

}

和gameFragment

public class MainGameFragment extends Fragment {

    @BindView(R.id.spinner_money)
    Spinner spinnerData;
    @BindView(R.id.text_profit_ill)
    TextView text_profit;
    @BindView(R.id.button_cash)
    Button btnCashCurrency;
    @BindView(R.id.restart_game)
    Button restartGame;
    @BindView(R.id.butonCurrency)
    Button buttonCurrency;

    public MainGameFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_game, container, false);


        CandleStickChart mChart = (CandleStickChart) view.findViewById(R.id.chart);

        mChart.getDescription().setEnabled(false);

        mChart.setMaxVisibleValueCount(40);

        mChart.animateX(3000);


        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setDrawGridLines(false);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setDrawGridLines(false);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setTextColor(Color.WHITE);

//        chart.getAxisLeft().setTextColor(...); // left y-axis
//        chart.getXAxis().setTextColor(...);
//        chart.getLegend().setTextColor(...);

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);

        ArrayList<CandleEntry> yVals1 = new ArrayList<>();
        int prog = ((int) (Math.random() * 80));

        for (int i = 0; i < prog; i++) {

            float val = (float) (Math.random() * 2);
            float high = (float) (Math.random() * 1) + 2f;
            float low = (float) (Math.random() * 1) + 2f;

            float open = (float) (Math.random() * 2) + 1f;
            float close = (float) (Math.random() * 2) + 1f;

            boolean even = i % 2 == 0;

            yVals1.add(new CandleEntry(i, val + high, val - low, even ? val + open : val - open,
                    even ? val - close : val + close));

            String date = String.valueOf(android.text.format.DateFormat.format("yyyy-MM-dd", new java.util.Date()));

            CandleDataSet set1 = new CandleDataSet(yVals1, date);

            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(Color.rgb(80, 80, 80));
            set1.setShadowColor(Color.DKGRAY);
            set1.setShadowWidth(0.7f);
            set1.setDecreasingColor(Color.RED);
            set1.setDecreasingPaintStyle(Paint.Style.FILL);
            set1.setIncreasingColor(Color.GREEN);
            set1.setIncreasingPaintStyle(Paint.Style.FILL);
            set1.setNeutralColor(Color.BLUE);
            set1.setHighlightLineWidth(1f);
            set1.setBarSpace(0.2f);

            CandleData data = new CandleData(set1);

            mChart.setData(data);
            mChart.invalidate();
            mChart.getLegend().setEnabled(false);
            ButterKnife.bind(this, view);
            configureSpinnerDataAndLogic();

        }
        return view;
    }

    @OnClick({R.id.btn_buy, R.id.btn_sell})
    public void onGlobalSearchClicked() {
        int cash = Integer.valueOf(btnCashCurrency.getText().toString());
        if (cash < 0) {
            restartGame.setVisibility(View.VISIBLE);
            Toast.makeText(getContext(), "Your cash is on -, u cant play. Please restart game.", Toast.LENGTH_SHORT).show();
        } else {
            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            ft.addToBackStack(null);
            int min = 0;
            int max = 2;
            Random r = new Random();
            int i1 = r.nextInt(max - min + 1) + min;
            String text = spinnerData.getSelectedItem().toString();
            int temp = Integer.parseInt(text);
            int temp2 = temp * 2;
            if (i1 == 0 || i1 == 1) {
                DialogFragment newFragment = LostDialogFragment.newInstance(1);
                String DIALOG_LOST = "LostDialogFragment";
                newFragment.show(ft, DIALOG_LOST);
                cash -= temp2;
                btnCashCurrency.setText(cash + "");
            } else {
                DialogFragment newFragment = WinDialogFragment.newInstance(1);
                String DIALOG_WIN = "WinDialogFragment";
                newFragment.show(ft, DIALOG_WIN);
                cash += temp2;
                btnCashCurrency.setText(cash + "");
            }
        }
    }

    @OnClick(R.id.restart_game)
    public void restartGame() {
        ((CurrencySelectActivity) getContext()).onBackPressed();
    }

//    @OnClick(R.id.button_cash)
//    public void openHistoryGames() {
//        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
//        ft.addToBackStack(null);
//        DialogFragment newFragment = GameHistoryFragment.newInstance(1);
//        String DIALOG_HISTORY = "HistoryDialogFragment";
//        newFragment.show(ft, DIALOG_HISTORY);
//    }

    private void configureSpinnerDataAndLogic() {
        String[] arraySpinner = new String[]{
                "50", "100", "150", "200", "250", "300", "500"
        };
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_item, arraySpinner);
        spinnerData.setAdapter(adapter);
        spinnerData.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String text = spinnerData.getSelectedItem().toString();
                int temp = Integer.parseInt(text);
                text_profit.setText((temp * 2) + " $ " + "100%");
            }

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

    }
}
作者: Rodriquez 的来源 发布者: 2017 年 2 月 14 日

回应 1


1

762 作者的声誉

决定

将位置传递给Activity的openGameFragment函数,如下所示:

holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((CurrencySelectActivity)mContext).openGameFragment(position+1);
            }
        });

在openGameFragment函数中将包添加到片段对象:

public void openGameFragment(int position) {
    mainGameFragment = new MainGameFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("button_position", position);
    mainGameFragment.setArguments(bundle);
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.activity_currency_select, mainGameFragment, "fragment")
            .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .commit();
}

在MainGameFragment的OnCreate中,从包中检索这些值。

private int buttonPosition;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            buttonPosition = getArguments().getInt("button_position", 0);
        }
    }

您可以以相同的方式将文本传递给bundle,并可以相应地使用这些值。

作者: nnn 发布者: 2017 年 2 月 14 日
32x32