-3

Estoy intentando resolver el juego del ahorcado en android ymi problema es que tengo un HorizontalScrollView, que contiene un Grid Layout.

Lo relleno con botones, uno por cada letra del alfabeto.

Mi problema es que los botones me los pone todos uno detras de otro y yo quiero que me lo muestre en varias lineas para que quede mas visual y no tener que estar desplazando la barra de Scroll para seleccionar los botones.

Si necesitais alguna foto o parte del codigo para aclararos pedidla.

Muchisimas gracias por adelantado!

2
  • el código va desde el inicio en la pregunta amigo, por eso tienes votos negativos
    – user75901
    el 18 dic. 2018 a las 21:18
  • Recuerda realizar tus preguntas en base a Cómo preguntar, modifica tu pregunta.
    – Jorgesys
    el 18 dic. 2018 a las 23:56

2 respuestas 2

0

Lo que puedes hacer es utilizar un recyclerView para generar los botones del alfabeto utilizando un Grid Layout.

aquí te dejo un ejemplo obtenido de Android RecyclerView Grid Layout Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

custom_view.xml

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardMaxElevation="4dp"
card_view:cardElevation="2dp"
card_view:contentPadding="5dp"
>
<LinearLayout
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="3dp"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#000"
        android:textSize="25dp"
        android:textStyle="bold"
        android:layout_margin="2dp"
        android:padding="10dp"
        android:layout_gravity="center"
        android:gravity="center"
        />
</LinearLayout>

MainActivity.java

import android.content.Context;

import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Window; import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity { private Context mContext;

RelativeLayout mRelativeLayout;
private RecyclerView mRecyclerView;

private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // Request window feature action bar
    requestWindowFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the application context
    mContext = getApplicationContext();

    // Change the action bar color
    getSupportActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#FF677589"))
    );

    // Get the widgets reference from XML layout
    mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    // Initialize a new String array
    String[] animals = {
            "Aardvark",
            "Albatross",
            "Alligator",
            "Alpaca",
            "Ant",
            "Anteater",
            "Antelope",
            "Ape",
            "Armadillo",
            "Donkey",
            "Baboon",
            "Badger",
            "Barracuda",
            "Bear",
            "Beaver",
            "Bee"
    };

    /*
        GridLayoutManager
            A RecyclerView.LayoutManager implementations that lays out items in a grid.
            By default, each item occupies 1 span. You can change it by providing a custom
            GridLayoutManager.SpanSizeLookup instance via setSpanSizeLookup(SpanSizeLookup).
    */
    /*
        public GridLayoutManager (Context context, int spanCount)
            Creates a vertical GridLayoutManager

        Parameters
            context : Current context, will be used to access resources.
            spanCount : The number of columns in the grid
    */
    // Define a layout for RecyclerView
    mLayoutManager = new GridLayoutManager(mContext,3);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // Initialize a new instance of RecyclerView Adapter instance
    mAdapter = new AnimalsAdapter(mContext,animals);

    // Set the adapter for RecyclerView
    mRecyclerView.setAdapter(mAdapter);

} }

AnimalsAdapter.java

import android.content.Context;

import android.graphics.Color; import android.graphics.EmbossMaskFilter; import android.graphics.drawable.GradientDrawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView;

import java.util.Random;

public class AnimalsAdapter extends RecyclerView.Adapter{ private String[] mDataSet; private Context mContext; private Random mRandom = new Random();

public AnimalsAdapter(Context context,String[] DataSet){
    mDataSet = DataSet;
    mContext = context;
}

public static class ViewHolder extends RecyclerView.ViewHolder{
    public TextView mTextView;
    public LinearLayout mLinearLayout;
    public ViewHolder(View v){
        super(v);
        mTextView = (TextView) v.findViewById(R.id.tv);
        mLinearLayout = (LinearLayout) v.findViewById(R.id.ll);
    }
}

@Override
public AnimalsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    // Create a new View
    View v = LayoutInflater.from(mContext).inflate(R.layout.custom_view,parent,false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position){
    holder.mTextView.setText(mDataSet[position]);
    // Generate a random color
    int color = getRandomHSVColor();

    // Set a random color for TextView background
    holder.mTextView.setBackgroundColor(getLighterColor(color));

    // Set a text color for TextView
    holder.mTextView.setTextColor(getReverseColor(color));

    // Set a gradient background for LinearLayout
    holder.mLinearLayout.setBackground(getGradientDrawable());

    // Emboss the TextView text
    applyEmbossMaskFilter(holder.mTextView);
}

@Override
public int getItemCount(){
    return mDataSet.length;
}

// Custom method to apply emboss mask filter to TextView
protected void applyEmbossMaskFilter(TextView tv){
    EmbossMaskFilter embossFilter = new EmbossMaskFilter(
            new float[]{1f, 5f, 1f}, // direction of the light source
            0.8f, // ambient light between 0 to 1
            8, // specular highlights
            7f // blur before applying lighting
    );
    tv.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
    tv.getPaint().setMaskFilter(embossFilter);
}

// Custom method to generate random HSV color
protected int getRandomHSVColor(){
    // Generate a random hue value between 0 to 360
    int hue = mRandom.nextInt(361);
    // We make the color depth full
    float saturation = 1.0f;
    // We make a full bright color
    float value = 1.0f;
    // We avoid color transparency
    int alpha = 255;
    // Finally, generate the color
    int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
    // Return the color
    return color;
}

// Custom method to create a GradientDrawable object
protected GradientDrawable getGradientDrawable(){
    GradientDrawable gradient = new GradientDrawable();
    gradient.setGradientType(GradientDrawable.SWEEP_GRADIENT);
    gradient.setColors(new int[]{getRandomHSVColor(), getRandomHSVColor(),getRandomHSVColor()});
    return gradient;
}

// Custom method to get a darker color
protected int getDarkerColor(int color){
    float[] hsv = new float[3];
    Color.colorToHSV(color, hsv);
    hsv[2] = 0.8f *hsv[2];
    return Color.HSVToColor(hsv);
}

// Custom method to get a lighter color
protected int getLighterColor(int color){
    float[] hsv = new float[3];
    Color.colorToHSV(color,hsv);
    hsv[2] = 0.2f + 0.8f * hsv[2];
    return Color.HSVToColor(hsv);
}

// Custom method to get reverse color
protected int getReverseColor(int color){
    float[] hsv = new float[3];
    Color.RGBToHSV(
            Color.red(color), // Red value
            Color.green(color), // Green value
            Color.blue(color), // Blue value
            hsv
    );
    hsv[0] = (hsv[0] + 180) % 360;
    return Color.HSVToColor(hsv);
}

}

build.gradle [dependencies]

implementation 'com.android.support:recyclerview-v7:28.0.0'

implementation 'com.android.support:cardview-v7:28.0.0'

Obtendrás el siguiente resultado

Resultado

En este caso tendrías que acomodar tu vista para mostrar como desees los botones

-1

Recuerda que solo puedes tener un View dentro de un ScrollView independientemente de la orientación deseada.

Yo lo que haría seria utilizar algo como lo siguiente:

<ScrollView> 
  <LinearLayout>
    <RelativeLayout>
     // aqui todos tus items que quieras utilizar para interactuar 
    <RelativeLayout/>
  <LinearLayout/>
<ScrollView/>

Obviamente llenando tus configuraciones a lo que necesites, si vas a tener cosas muy interactivas te recomendaría ir mas avanzado y separarlo en fragments.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.